package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.PickUpAddressesEntity;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.L;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class MyPickupAddressActivity extends BaseActivity {
    private ListView mListView;
    private RelativeLayout nodate_ll;
    private TextView nodate_start;

    private TextView lastView;
    private List<PickUpAddressesEntity> mDataList = new ArrayList<>();
    private boolean isFirst;
    private BaseAdapter adapter;
    Context mContext;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myaddress);
        nodate_start = (TextView) findViewById(R.id.nodate_start);
        nodate_start.setOnClickListener(this);
        mListView = (ListView) findViewById(R.id.listview);
        View llAdd = findViewById(R.id.ll_add);
        mListView.setEmptyView(llAdd);
        mContext = this;
        toolbarTitle.setText("提货地址");
        tvBack.setVisibility(View.VISIBLE);
        ivBack.setVisibility(View.VISIBLE);
//        righticon.setImageDrawable(getResources().getDrawable(R.mipmap.my_add));
//        righticon.setVisibility(View.VISIBLE);
        righticon.setOnClickListener(this);
        initAdapter();
    }

    private void initAdapter() {
        adapter = new CommonAdapter<PickUpAddressesEntity>(mContext, mDataList,
                R.layout.item_adress) {
            @Override
            public int getCount()
            {
                if(mDatas==null){
                    return 0;
                }
                if(mDatas.size()>=1){
                    return 1;
                }
                return mDatas.size();
            }
            @Override
            public void convert(final ViewHolder holder, final PickUpAddressesEntity bean) {
                holder.setText(R.id.address_name, bean.getProvinceName()+bean.getCityName() + bean.getDistrictName() + bean.getAddress());
                holder.setText(R.id.name,bean.getContactName());
                holder.setText(R.id.phone,bean.getTel());
                holder.setText(R.id.new_name,bean.getName());

                L.d("bean","bean"+bean);
                holder.setOnClickListener(R.id.edit, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent edit = new Intent(getApplicationContext(), NewPickupAddressActivity.class);
                        edit.putExtra("provinceId", bean.getProvinceId());
                        edit.putExtra("cityId", bean.getCityId());
                        edit.putExtra("districtId", bean.getDistrictId());
                        edit.putExtra("provinceName", bean.getProvinceName());
                        edit.putExtra("cityName", bean.getCityName());
                        edit.putExtra("districtName", bean.getDistrictName());
                        edit.putExtra("id", bean.getUuid());
                        edit.putExtra("address", bean.getAddress());
                        edit.putExtra("name", bean.getName());
                        edit.putExtra("phone", bean.getTel());
                        edit.putExtra("contactName", bean.getContactName());
                        edit.putExtra("post_code", bean.getName());

                        startActivityForResult(edit,0x123);
                    }
                });
                holder.setOnClickListener(R.id.delete, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                        //new CustomDialog.Builder(mContext)//.setTitle("是否删除")//设置对话框标题
                        //.setMessage("一旦删除，不可更改")//设置显示的内容
                        builder.setTitleVisible(false).setMessage("确定删除地址吗？")//设置显示的内容
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                        mHttpDelete(bean.getUuid());
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//响应事件
                                dialog.dismiss();
                                // TODO Auto-generated method stub
                            }

                        });//在按键响应事件中显示此对话框
                        builder.create().show();
                    }
                });
            }
        };
        mListView.setAdapter(adapter);
        mHttpLoad();
    }

    @Override
    protected void onResume() {

        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK&&requestCode == 0x123){

            mHttpLoad();
        }
    }

    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.righticon:
            case R.id.nodate_start:
                Intent add = new Intent(getApplicationContext(),
                        NewPickupAddressActivity.class);
                startActivityForResult(add,0x123);
                break;
        }
    }



    /**
     * 加载地址列表数据
     */
    private void mHttpLoad() {

        SharedPreferences sp = FileUtil.getSharedPreferences();
        String str = sp.getString(Constant.KEY_PICK_UP_ADDRESS+"_"+getUser().getAccountId(), "");
        if (!TextUtils.isEmpty(str)) {
            List<PickUpAddressesEntity> list = new Gson().fromJson(str, new TypeToken<List<PickUpAddressesEntity>>() {
            }.getType());
            if (list == null || list.size() < 1) {
                //没有本地地址存储


            } else {
                mDataList.clear();
                mDataList.addAll(list);
                adapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 删除地址
     */
    private void mHttpDelete(String id) {
        if (id == null){
            return;
        }
        if (mDataList.size() > 0) {
            for (int i=0;i<mDataList.size();i++){

                if(id.equals(mDataList.get(i).getUuid())){
                    mDataList.remove(i);
                    break;
                }
            }
            adapter.notifyDataSetChanged();
            SharedPreferences sp = FileUtil.getSharedPreferences();
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(Constant.KEY_PICK_UP_ADDRESS +"_"+getUser().getAccountId(),new Gson().toJson(mDataList));
            edit.commit();
        }

//        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
//        data.setCmd("account/deliveryAddress/setDeleted");
//        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
//        Map<String, String> map = new HashMap<>();
//        data.setToken(getUser().getToken());
//        map.put("accountId", getUser().getAccountId());
//        data.setParameters(map);
//        requestSilent(data, "setDeleted", onRequestListenerDelete);
    }


}
